<template>
  <VPage>
    <VTable ref="tableRef" v-if="load" v-bind="tableOptions" class="is--card">
      <template #form="{ form }">
        <VSelect v-model="form.supplier_name" placeholder="供应商" type="supplierName" allow-create style="min-width: 200px" multiple collapse-tags clearable filterable />
        <VSelect v-model="form.month" placeholder="货款所属期" :options="monthOptions" style="min-width: 160px" />
        <VSelect v-model="form.company_id" placeholder="公司主体" :options="options.company_id" multiple collapse-tags style="min-width: 220px" />
        <VCascader v-model="form.department_name" placeholder="需求部门" type="department" multiple collapse-tags checkStrictly filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.period_id" placeholder="结算方式" type="period" multiple collapse-tags style="min-width: 220px" />
        <VSelect v-model="form.currency" placeholder="币种" :options="options.currency" multiple collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.purchase_user_id" placeholder="采购人员" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-if="[1, 2].includes(type)" v-model="form.snapshot_cycle" placeholder="历史周期" :options="options.snapshot_cycle" select style="width: 268px" />
        <VSelect v-else-if="[5].includes(type)" v-model="form.snapshot_cycle" placeholder="历史周期" :options="options.snapshot_cycle_month" select style="width: 160px" />
        <VSelect v-if="type === 3" v-model="form.status" placeholder="是否确认" :options="options.status" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.cash_type" placeholder="货款类型" :options="options.cash_type" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <div class="v-group-item">需求付款日期</div>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <el-tabs v-model="type" class="w-full" @tab-click="typeChange">
          <el-tab-pane v-for="(d, i) in typeOptions" :key="i" :label="d.label" :name="d.value"></el-tab-pane>
        </el-tabs>
        <template v-if="type === 3">
          <VButton auth="/purchase/manage/plan/add" :loading="loadings.add" type="primary" @click="handleRow('add')"><i class="dk-iconfont icon-Plus" />添加</VButton>
          <VButton auth="/purchase/manage/plan/batch" :loading="loadings.confirm" @click="handleBatch('confirm')">批量确认
          </VButton>
          <VButton auth="/purchase/manage/plan/updateTime" :loading="loadings.updateTime" @click="handleBatch('updateTime')">修改需求付款日期
          </VButton>
          <VButton auth="/purchase/manage/plan/remark" :loading="loadings.remark" @click="handleBatch('remark')">批量备注
          </VButton>
          <VButton auth="/purchase/manage/plan/delete" :loading="loadings.delete" @click="handleBatch('delete')">批量删除
          </VButton>
        </template>
        <!-- { 1: '历史周资金计划' }, { 2: '历史四周资金计划' }, { 3: '下周资金计划' }, { 4: '后四周资金计划' } -->
        <div class="flex gap-2" :class="type === 3 && 'ml-auto'">
          <VImport v-if="type === 3" auth="/purchase/manage/plan/import" :tableRef="tableRef" importUrl="/v1/cash-plan/cash-plan/import"
            downloadUrl="https://xc-pms.oss-cn-shenzhen.aliyuncs.com/template/下周资金计划导入模版.xlsx" @success="query" />
          <VExport auth="/purchase/manage/plan/derive" mainKey="cp_id"
            :name="['','cash_plan_history', 'cash_plan_history_four', 'cash_plan_next', 'cash_plan_next_four', 'cash_plan_month'][type]" :tableRef="tableRef" task />
          <VExport auth="/purchase/manage/plan/derive" mainKey="cp_id" name="cash_plan_detail" :tableRef="tableRef" task>导出明细</VExport>
        </div>
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <UPdateTime ref="updateTimeRef" :options="options" @success="query" />
    <VLog ref="logRef" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import Add from './components/Add'
import UPdateTime from './components/UPdateTime'
import { getOption } from '@/api/public'
import tableOpts from './tableOptions'
import { resMessage } from '@/utils/res'
import { ElMessage, ElMessageBox } from 'element-plus'
import VImport from '@/components/VImport'

const baseName = 'cash_plan'
const tableRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const updateTimeRef = ref()
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const cp_ids = selection.map(d => d.cp_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    updateTime: () => {
      updateTimeRef?.value.open(cp_ids)
    },
    delete: () => {
      ElMessageBox.confirm('是否确认删除？', '提示', {
        confirmButtonClass: 'messagebox-confirm-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.delete({ cp_ids }).then(res => {
            resMessage({
              res,
              success: () => {
                ElMessage.success('操作成功')
                query()
              }
            })
          }).finally(closeLoading)
        })
        .catch(() => {
          closeLoading()
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
    },
    confirm: () => {
      ElMessageBox.prompt('原因', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (val) => !val ? '不能为空' : true,
        inputType: 'textarea',
      })
        .then(({ value }) => {
          showLoading()
          api.confirm({ cp_ids, confirm_remark: value }).then(res => {
            ElMessage.success('操作成功')
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
    },
    remark: () => {
      ElMessageBox.prompt('备注', '批量修改备注', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (val) => !val ? '不能为空' : true,
        inputType: 'textarea',
      })
        .then(({ value }) => {
          showLoading()
          api.remark({ cp_ids, remark: value }).then(res => {
            resMessage({
              res,
              success: () => {
                ElMessage.success('操作成功')
                query()
              }
            })
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
    },
  }
  handle[name]()
}

// 单行操作
const addRef = ref()
const logRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { cp_id } = row || {}
  const showLoading = () => loadings[name + rowIndex] = true
  const closeLoading = () => loadings[name + rowIndex] = false
  const handle = {
    add: () => addRef?.value.open(),
    edit: () => addRef?.value.open(cp_id),
    editPrice: () => {
      const total_price = ref(row.total_price)
      ElMessageBox({
        title: '修改货款总额',
        message: () => <el-input-number v-model={total_price.value} controls={false} min={0} precision={2} placeholder="请输入" class="w-full" />
      }).then(res => {
        api.editPrice({cp_id, total_price: total_price.value}).then(res => {
          ElMessage.success('操作成功')
          query()
        }).finally(closeLoading)
      })
    },
    delete: () => {
      ElMessageBox.confirm('是否确认删除？', '提示', {
        confirmButtonClass: 'messagebox-confirm-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.delete({ cp_ids: [cp_id] }).then(res => {
            resMessage({
              res,
              success: () => {
                ElMessage.success('操作成功')
                query()
              }
            })
          }).finally(closeLoading)
        })
        .catch(() => {
          closeLoading()
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
    },
    confirm: () => {
      ElMessageBox.prompt('原因', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (val) => !val ? '不能为空' : true,
        inputType: 'textarea',
      })
        .then(({ value }) => {
          showLoading()
          api.confirm({ cp_ids: [cp_id], confirm_remark: value }).then(res => {
            ElMessage.success('操作成功')
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, cp_id })
    },
  }
  handle[name]()
}

// 列表配置
const type = ref(3)
const typeOptions = ref([
  { label: '历史周资金计划', value: 1 },
  { label: '历史四周资金计划', value: 2 },
  // { label: '本周资金计划', value: 6 },
  { label: '下周资金计划', value: 3 },
  { label: '后四周资金计划', value: 4 },
  { label: '月度资金计划', value: 5 }])
const monthOptions = ref([])

const setOptions = ({ month }) => {
  monthOptions.value = month?.map(d => ({ label: d, value: d }))
}
const load = ref(true)
const tableOptions = ref(tableOpts[type.value](setOptions))
const typeChange = async ({ paneName }) => {
  type.value = paneName
  load.value = false
  const data = {}
  if([1, 2].includes(type.value)) {
    data.snapshot_cycle = options.value.snapshot_cycle_month?.findLast(d => d)?.value??''
  }
  tableOptions.value = tableOpts[type.value](setOptions, handleRow, data)
  await 1
  load.value = true
}
</script>
  